#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QPainter>
#include <QPen>
#include <QBrush>
#include <QTime> // 引入QTime用于获取当前时间

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    timeId = startTimer(1000); // 1000ms定时器
}

Widget::~Widget()
{
    delete ui;
}

void Widget::paintEvent(QPaintEvent *event){
    Q_UNUSED(event);

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true); // 抗锯齿

    int side = qMin(width(), height());
    painter.setViewport((width() - side) / 2, (height() - side) / 2, side, side);//设置视口
    painter.setWindow(-50, -50, 100, 100);//窗口

    QPen pen(Qt::black);
    QBrush brush(Qt::white);
    painter.setPen(pen);
    painter.setBrush(brush);

    // 绘制钟面
    painter.drawEllipse(QPointF(0, 0), 50, 50);

    // 获取当前时间
    QTime currentTime = QTime::currentTime();

    // 计算角度
    double secAngle = (currentTime.second() * 6) - 90;
    double minAngle = (currentTime.minute() * 6 + currentTime.second() / 10.0) - 90;
    double hourAngle = (currentTime.hour() % 12 * 30 + currentTime.minute() / 2.0) - 90;

    // 绘制秒针
    painter.save();
    painter.rotate(secAngle);
    painter.setPen(QPen(Qt::red, 1));
    painter.drawLine(0, 0, 0, -40);
    painter.restore();

    // 绘制分针
    painter.save();
    painter.rotate(minAngle);
    painter.setPen(QPen(Qt::black, 2));
    painter.drawLine(0, 0, 0, -35);
    painter.restore();

    // 绘制时针
    painter.save();
    painter.rotate(hourAngle);
    painter.setPen(QPen(Qt::black, 3));
    painter.drawLine(0, 0, 0, -30);
    painter.restore();

    // 绘制中心点
    painter.setBrush(Qt::black);
    painter.drawEllipse(QPointF(0, 0), 5, 5);
}

void Widget::timerEvent(QTimerEvent *event)// 定时器事件处理器
{
    if (event->timerId() == timeId) {
        update(); // 更新窗口，触发重绘
    }
}



